<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :fullscreen.sync="fullscreen"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
    :maskClosable="false"
    @cancel="handleCancel"
    :footer="null"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title" label="标题">
          <a-input v-model="model.title" allowClear style="width: 350px"></a-input>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts" label="适用门店">
          <a-cascader
            :options="departModel.departTreeOptions"
            @change="onDepartChange"
            :showSearch="true"
            expand-trigger="hover"
            placeholder=""
            :fieldNames="fieldNames"
            style="width: 350px"
            v-model="model.selecteddeparts"
          />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="couponName" label="优惠券">
          <a-input v-model="model.couponName" style="width: 270px; margin-right: 5px" readOnly></a-input
          ><a-button type="primary" icon="search" @click="handleSelectCoupon">选择</a-button>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateRange" label="领取时间">
          <a-range-picker
            :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }"
            format="YYYY-MM-DD HH:mm:ss"
            v-model="model.dateRange"
            @change="handleDateChange1"
          />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="getNumLimit" label="每人限领(张)">
          <a-input-number
            v-model="model.getNumLimit"
            allowClear
            style="width: 350px"
            :min="1"
            :max="999"
            :formatter="limitNumber"
            :parser="limitNumber"
          ></a-input-number>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
          <a-col :md="24" :sm="24">
            <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
              <a-button type="primary" htmlType="submit" @click="handleOk">保存</a-button>
            </a-form-model-item>
          </a-col>
        </a-form-model-item>
      </a-form-model>
      <SelectCouponList ref="selectCouponForm" @ok="selectOk"></SelectCouponList>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import moment from 'moment'
import { limitNumber, filterObj } from '@/utils/util'
import { queryDepartTreeList1 } from '@/api/api'
import SelectCouponList from './SelectCouponList'

export default {
  name: 'PosMarketScanSenceModal',
  components: {
    SelectCouponList,
  },
  data() {
    return {
      title: '操作',
      visible: false,
      fullscreen: true,
      departModel: {
        departTreeOptions: [],
        orgIds: '',
        orgNames: '',
      },
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      model: {
        showScope: false,
      },
      moment,
      limitNumber,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },

      confirmLoading: false,
      validatorRules: {
        dateRange: [{ required: true, message: '必填项' }],
        title: [{ required: true, message: '必填项' }],
        selecteddeparts: [{ required: true, message: '必填项' }],
        couponName: [{ required: true, message: '必填项' }],
        getNumLimit: [{ required: true, message: '必填项' }],
      },
      url: {
        add: '/marketing/sence/posMarketSence/add',
        edit: '/marketing/sence/posMarketSence/edit',
      },
    }
  },
  created() {
    this.loadDepartTree()
  },
  methods: {
    selectOk(result){
      console.log('result', result)
      if(result && result.length > 0){
        console.log('callback set value')
        this.$set(this.model,'couponName' , result[0].actNm)
        this.$set(this.model,'couponId' , result[0].couponId)
      }
    },
    handleSelectCoupon(){
      let selecteddeparts = this.model.selecteddeparts
      if(!selecteddeparts || selecteddeparts.length == 0){
        this.$message.warning('请选择适用门店')
        return false
      }
      this.$refs.selectCouponForm.search(selecteddeparts, this.model)
      this.$refs.selectCouponForm.title = '选择优惠券'
      this.$refs.selectCouponForm.visible = true
    },
    loadDepartTree() {
      let that = this
      queryDepartTreeList1({ orgTypes: '2' }).then((res) => {
        if (res.success) {
          that.$set(that.departModel, 'departTreeOptions', res.result)
          console.log('departTreeOptions', that.departModel.departTreeOptions)
          that.departModel.departTreeOptions.forEach((x) => {
            x['children'] = [{ title: '全部门店', value: '0' }]
          })
        }
      })
    },
    onDepartChange(value, selectedOptions) {
      console.log('value:', value)
      console.log('selectedOptions:', selectedOptions)
      this.departModel.orgIds = value && value.length > 0 ? value[0] : ''
      this.departModel.orgNames = selectedOptions && selectedOptions.length > 0 ? selectedOptions[0].departName : ''
      this.$set(this.model, 'planNm', this.departModel.orgNames + '的积分方案')
    },
    handleDateChange1(date, dateString) {
      this.model.startTime = dateString[0]
      this.model.endTime = dateString[1]
    },
    add() {
      //初始化默认值
      this.edit({})
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.assembleFileld(record)
    },
    assembleFileld(record){
      if(record.id){
        this.$set(this.model,'selecteddeparts' , [record.senceShopList[0].orgId,0])
        this.$set(this.model, 'couponId' , record.senceDetailList[0].releatedId)
        this.$set(this.model, 'getNumLimit' , record.senceDetailList[0].num)
        this.$set(this.model, 'couponName' , record.senceDetailList[0].couponName)
        this.$set(this.model, 'dateRange', [moment(record.startTime), moment(record.endTime)])
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    buildReqVo(){
      let params = Object.assign({}, this.model)
      params['senceType'] = 10
      params['posMarketSenceDetailSaveReqVos'] = [{
        taskType: 'COUPON',
        releatedId: this.model.couponId,
        num: this.model.getNumLimit,
        remark : '',
      }]

      params['posMarketSenceShopSaveReqVos'] = [{
        orgId: this.model.selecteddeparts[0],
        shopId: '0',
      }]

      params = filterObj(params)

      console.log('reqVo', params)

      return params
    },
    checkParams(params){
      // if(params.getNumLimit > params.distTotal){
      //   this.$message.warning('领取数量不能超过发券数量')
      //   return false
      // }
      return true
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let params = this.buildReqVo()

          if(!this.checkParams(params)){
            return false
          }

          httpAction(httpurl, params, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
  },
}
</script>

<style lang="less" scoped>
</style>